<template>
  <div class="delivery-address" style="height: 800px;">
    <!-- 顶部操作按钮 -->
    <el-row :gutter="10" class="mb-2">
      <el-col :span="2">
        <el-button type="primary" @click="openAddDialog">新增</el-button>
      </el-col>
      <el-col :span="2">
        <el-button @click="handleRefresh">刷新</el-button>
      </el-col>
    </el-row>

    <!-- 地址列表表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="操作"
        width="120"
      >
        <template #default="scope">
          <el-tooltip content="修改地址信息" placement="top">
            <el-button type="text" @click="handleEdit(scope.row)" size="small">
              <el-icon><i class="el-icon-edit" /></el-icon>
              <span>修改</span>
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除该地址" placement="top">
            <el-button type="text" @click="handleDelete(scope.row)" size="small" class="ml-2" text-color="red">
              <el-icon><i class="el-icon-delete" /></el-icon>
              <span>删除</span>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        prop="addressAlias"
        label="地址简称"
      />
      <el-table-column
        prop="contactName"
        label="联系人"
      />
      <el-table-column
        prop="contactPhone"
        label="联系电话"
      />
      <el-table-column
        prop="phoneNumber"
        label="手机号码"
      />
      <el-table-column
        prop="province"
        label="省"
      />
      <el-table-column
        prop="city"
        label="市"
      />
      <el-table-column
        prop="district"
        label="区"
      />
      <el-table-column
        prop="detailedAddress"
        label="详细地址"
      />
      <el-table-column
        prop="postalCode"
        label="邮政编码"
      />
      <el-table-column
        prop="isDefault"
        label="默认地址"
        width="80"
      >
        <template #default="scope">
          <el-tag>{{ scope.row.isDefault ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="addressFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="地址简称" prop="addressAlias">
          <el-input v-model="form.addressAlias" placeholder="请输入地址简称" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="默认地址" prop="isDefault">
          <el-switch v-model="form.isDefault" />
        </el-form-item>
        <el-form-item label="省" prop="province">
          <el-select v-model="form.province" placeholder="请选择省" @change="handleProvinceChange">
            <el-option
              v-for="item in provinceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="form.city" placeholder="请选择市" @change="handleCityChange">
            <el-option
              v-for="item in cityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区" prop="district">
          <el-select v-model="form.district" placeholder="请选择区">
            <el-option
              v-for="item in districtOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="邮政编码" prop="postalCode">
          <el-input v-model="form.postalCode" placeholder="请输入邮政编码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟省市区数据
const provinceOptions = ref([
  { label: '广东省', value: '广东省' },
  { label: '湖南省', value: '湖南省' }
])
const cityOptions = ref([])
const districtOptions = ref([])

// 表格数据
const tableData = ref([
  {
    addressAlias: '公司地址',
    contactName: '研发中心',
    contactPhone: '0755-12345678',
    phoneNumber: '123****4299',
    province: '广东省',
    city: '深圳市',
    district: '南山区',
    detailedAddress: '科技园区8栋15楼',
    postalCode: '518000',
    isDefault: true
  }
])

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增发货地址')
const form = reactive({
  addressAlias: '',
  contactPhone: '',
  phoneNumber: '',
  contactName: '',
  isDefault: false,
  province: '',
  city: '',
  district: '',
  detailedAddress: '',
  postalCode: ''
})

// 表单校验规则
const rules = reactive({
  addressAlias: [{ required: true, message: '请输入地址简称', trigger: 'blur' }],
  phoneNumber: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  contactName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  province: [{ required: true, message: '请选择省', trigger: 'change' }],
  city: [{ required: true, message: '请选择市', trigger: 'change' }],
  district: [{ required: true, message: '请选择区', trigger: 'change' }],
  detailedAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
})

// 表单引用
const addressFormRef = ref(null)

onMounted(() => {
  // 初始化数据
})

// 打开新增弹窗
const openAddDialog = () => {
  resetForm()
  dialogTitle.value = '新增发货地址'
  dialogVisible.value = true
}

// 编辑地址
const handleEdit = (row) => {
  dialogTitle.value = '编辑发货地址'
  dialogVisible.value = true
  // 赋值表单
  for (const key in form) {
    form[key] = row[key]
  }
}

// 删除地址
const handleDelete = (row) => {
  ElMessageBox.confirm('此操作将永久删除该地址, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = tableData.value.findIndex(item => item === row)
    if (index !== -1) {
      tableData.value.splice(index, 1)
    }
    ElMessage.success('删除成功!')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 保存地址（新增/编辑）
const handleSave = () => {
  addressFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogTitle.value === '新增发货地址') {
        // 模拟新增逻辑
        tableData.value.push({ ...form })
      } else {
        // 模拟编辑逻辑
        const index = tableData.value.findIndex(item => item.addressAlias === form.addressAlias)
        if (index !== -1) {
          tableData.value[index] = { ...form }
        }
      }
      dialogVisible.value = false
      ElMessage.success('操作成功')
    } else {
      ElMessage.error('请填写完整必填项')
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  for (const key in form) {
    form[key] = ''
  }
  form.isDefault = false
  cityOptions.value = []
  districtOptions.value = []
}

// 省改变时加载市
const handleProvinceChange = (val) => {
  if (val === '广东省') {
    cityOptions.value = [
      { label: '深圳市', value: '深圳市' },
      { label: '广州市', value: '广州市' }
    ]
  } else if (val === '湖南省') {
    cityOptions.value = [
      { label: '长沙市', value: '长沙市' },
      { label: '衡阳市', value: '衡阳市' }
    ]
  }
  form.city = ''
  form.district = ''
  districtOptions.value = []
}

// 市改变时加载区
const handleCityChange = (val) => {
  if (form.province === '广东省' && val === '深圳市') {
    districtOptions.value = [
      { label: '南山区', value: '南山区' },
      { label: '福田区', value: '福田区' }
    ]
  } else if (form.province === '广东省' && val === '广州市') {
    districtOptions.value = [
      { label: '天河区', value: '天河区' },
      { label: '越秀区', value: '越秀区' }
    ]
  }
  form.district = ''
}

// 刷新
const handleRefresh = () => {
  ElMessage.info('数据已刷新')
}
</script>

<style scoped>
.delivery-address {
  padding: 20px;
}
.mb-2 {
  margin-bottom: 10px;
}
.dialog-footer {
  text-align: right;
}
.ml-2 {
  margin-left: 10px;
}
/* 操作按钮样式优化 */
.el-table .el-button {
  display: flex;
  align-items: center;
  padding: 0;
  justify-content: center;
}
.el-table .el-icon {
  margin-right: 4px;
}

</style>